/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.extended.codegen.manager;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.common.util.lang.NamingCase;
import org.elsfs.cloud.extended.codegen.entity.GenFieldType;
import org.elsfs.cloud.extended.codegen.entity.GenTableColumn;
import org.elsfs.cloud.extended.codegen.repository.GenFieldTypeRepository;
import org.elsfs.cloud.extended.codegen.repository.GenTableColumnRepository;
import org.springframework.stereotype.Service;

/**
 * 表字段信息管理 管理
 *
 * @author zeng
 */
@Service
@RequiredArgsConstructor
public class GenTableColumnManager {
  private final GenTableColumnRepository genTableColumnRepository;
  private final GenFieldTypeRepository genFieldTypeRepository;

  /**
   * 初始化表单字段列表，主要是将数据库表中的字段转化为表单需要的字段数据格式，并为审计字段排序
   *
   * @param tableFieldList 表单字段列表
   */
  public void initFieldList(List<GenTableColumn> tableFieldList) {
    // 字段类型、属性类型映射
    List<GenFieldType> list = genFieldTypeRepository.list();
    Map<String, GenFieldType> fieldTypeMap = new LinkedHashMap<>(list.size());
    list.forEach(
        fieldTypeMapping ->
            fieldTypeMap.put(fieldTypeMapping.getColumnType().toLowerCase(), fieldTypeMapping));

    // 索引计数器
    AtomicInteger index = new AtomicInteger(0);
    tableFieldList.forEach(
        field -> {
          // 将字段名转化为驼峰格式
          field.setAttrName(NamingCase.toCamelCase(field.getFieldName()));

          // 获取字段对应的类型
          GenFieldType fieldTypeMapping =
              fieldTypeMap.getOrDefault(field.getFieldType().toLowerCase(), null);
          if (fieldTypeMapping == null) {
            // 没找到对应的类型，则为Object类型
            field.setAttrType("Object");
          } else {
            field.setAttrType(fieldTypeMapping.getAttrType());
            field.setPackageName(fieldTypeMapping.getPackageName());
          }

          // 设置查询类型和表单查询类型都为“=”
          field.setQueryType("=");
          field.setQueryFormType("text");

          // 设置表单类型为文本框类型
          field.setFormType("text");

          // 保证审计字段最后显示
          field.setSort(
              Objects.isNull(field.getSort()) ? index.getAndIncrement() : field.getSort());
        });
  }

  /**
   * 更新指定数据源和表名的表单字段信息
   *
   * @param dsName 数据源名称
   * @param tableName 表名
   * @param tableFieldList 表单字段列表
   */
  public void updateTableField(
      String dsName, String tableName, List<GenTableColumn> tableFieldList) {
    AtomicInteger sort = new AtomicInteger();
    List<GenTableColumn> collect =
        tableFieldList.stream().peek(field -> field.setSort(sort.getAndIncrement())).toList();
    genTableColumnRepository.updateBatchById(collect);
  }
}
